package com.zhangmeng.tools.controller;

import com.zhangmeng.tools.utils.AlertUtils;
import com.zhangmeng.tools.utils.ImagePath;
import com.zhangmeng.tools.utils.JksUtils;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import org.bouncycastle.util.encoders.Base64;

import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.Enumeration;

/**
 * @author : 芊芊墨客
 * @version : 1.0
 * @date : 2023-05-06 16:43
 */
public class JksFileController {

    @FXML
    public TextField dir;

    @FXML
    public Button choose_file;


    @FXML
    public Button x509_gen;

    @FXML
    public TextField jks_file_name;

    @FXML
    public TextField cer_file_name;

    @FXML
    public Button jks_gen;

    @FXML
    public TextArea jks_public;

    @FXML
    public TextArea cer_public;

    @FXML
    public TextArea jks_private;


    @FXML
    public void initialize() {
        choose_file.setText(null);
        ImageView iv = new ImageView(new Image(ImagePath.path(ImagePath.ImagePathType.IMAGE_FILE)));
        iv.setPreserveRatio(true);
        iv.setFitWidth(18);
        choose_file.setGraphic(iv);

        choose_file.setOnAction(event -> {
            Stage stage = new Stage();
            DirectoryChooser dc = new DirectoryChooser();
            dc.setTitle("文件夹选择器");
            File file = dc.showDialog(stage);
            if (file != null) {
                String path = file.getAbsolutePath();
                dir.setText(path);
            }
        });

        x509_gen.setOnAction(event -> {

            if (dir.getText().length() == 0) {
                AlertUtils.alert_warning("文件夹不能为空!");
                return;
            }

            String content = JksUtils.GetCertFile.x509Certificate(dir.getText());
            cer_public.setText(content);

        });

        jks_gen.setOnAction(event -> {

            if (dir.getText().length() == 0) {
                AlertUtils.alert_warning("文件夹不能为空!");
                return;
            }

            if (jks_file_name.getText().length() == 0) {
                AlertUtils.alert_warning("jks文件名不能为空!");
                return;
            }

            JksUtils.GetJksAndCerFile.jks_cer(dir.getText() + jks_file_name.getText(), "123456", "123456", dir.getText() + cer_file_name.getText());
            Path path = Paths.get(dir.getText() + jks_file_name.getText());
            Path path2 = Paths.get(dir.getText() + cer_file_name.getText());

                new Thread(()->{
                    while (true){
                        if (Files.exists(path)){
                            break;
                        }
                    }
                    try {
                        readJks(dir.getText() + jks_file_name.getText(), "123456");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }).start();

                new Thread(()->{
                    while (true){
                        if (Files.exists(path2)){
                            break;
                        }
                    }
                    try {
                        readCer(dir.getText() + cer_file_name.getText());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }).start();

                //&& Files.exists(path2)
//                JksUtils.GetJksAndCerFile.readJks(dir.getText() + jks_file_name.getText(), "123456");
//                JksUtils.GetJksAndCerFile.readCer(dir.getText() + cer_file_name.getText());
        });
    }

    //读取证书文件获取公钥
    public void readCer(String file) throws Exception {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        Certificate certificate = certificateFactory.generateCertificate(new FileInputStream(file));
        PublicKey publicKey = certificate.getPublicKey();
        String cer =  new String(Base64.encode(publicKey.getEncoded()));
        cer_public.setText(cer);
    }

    //读取jks文件获取公、私钥
    public  void readJks(String file,String keypass) throws Exception {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(new FileInputStream(file), keypass.toCharArray());
        Enumeration<String> aliases = keyStore.aliases();
        String alias = null;
        while (aliases.hasMoreElements()) {
            alias = aliases.nextElement();
        }
        PrivateKey key = (PrivateKey) keyStore.getKey(alias, keypass.toCharArray());

        Certificate certificate = keyStore.getCertificate(alias);
        PublicKey publicKey = certificate.getPublicKey();
        String jks_p =  new String(Base64.encode(publicKey.getEncoded()));
        String private_key = new String(Base64.encode(key.getEncoded())) ;

        Platform.runLater(()->{
            jks_private.setText(private_key);
            jks_public.setText(jks_p);
        });
    }
}
